package com.mjk.common.tools.lock.distrib.impl;

import com.mjk.common.tools.lock.SegmentLock;
import com.mjk.common.tools.lock.distrib.DistributedLock;

import java.util.HashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 默认锁 如果Redis 和 zookepper 都没开的情况下 默认锁
 */
public class DefaultLock implements DistributedLock {
    private Integer segments = 16;

    private final String instance = new String();

    private final HashMap<Object, ReentrantLock> lockMap = new HashMap<>();

    public DefaultLock() {
        init(null, false);
    }

    public DefaultLock(Integer counts, boolean fair) {
        init(counts, fair);
    }

    private void init(Integer counts, boolean fair) {
        if (counts != null) {
            segments = counts;
        }
        for (int i = 0; i < segments; i++) {
            lockMap.put(i, new ReentrantLock(fair));
        }
    }

    public boolean lock(String key) {
        if (key == null) {
            key = instance;
        }
        int index = (key.hashCode() >>> 1) % segments;
        ReentrantLock lock = lockMap.get(index);
        return lock.tryLock();
    }

    public void releaseLock(String key) {
        if (key == null) {
            key = instance;
        }
        int index = (key.hashCode() >>> 1) % segments;
        ReentrantLock lock = lockMap.get(index);
        lock.unlock();
    }
}
